﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Windows.Forms;

namespace Demo_LoopShow
{
    public partial class Frm_LoopShow : Form
    {
        Bitmap bitmap;
        int total = 0;
        Thread thShow;
        private ManualResetEvent evtShow = new ManualResetEvent(false);
        System.Threading.Timer timer;
        Random random = new Random();
        public Frm_LoopShow()
        {
            InitializeComponent();
            snsPictureBox1.IsSawtooth = true;//开启后像素颗粒感比较强
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //创建图像
            bitmap = new Bitmap(2048,1600,PixelFormat.Format24bppRgb);
            //给图像涂上背景色
            Graphics gs = Graphics.FromImage(bitmap);
            gs.FillRectangle(new SolidBrush(Color.FromArgb(255, 8, 8, 10)), new Rectangle(0, 0, bitmap.Width, bitmap.Height));
            gs.Dispose();
            //开启一个定时器，用于图像显示信号的输出
            timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimerEvent), null, 0, 10);//单位ms
            //创建专门用于图像显示的线程
            thShow = new Thread(ShowImage);
            thShow.IsBackground = true;
            thShow.Start();
        }

        private void TimerEvent(object a)
        {
            //记录当前图像的数量
            total++;
            //给图像显示线程发送信号
            evtShow.Set();
        }

        private void ShowImage()
        {
            while (true)
            {
                evtShow.WaitOne(); //等待图像显示信号
                int x = random.Next(10, bitmap.Width - 10);
                int y = random.Next(10, bitmap.Height - 10);
                int r = random.Next(0, 255);
                int g = random.Next(0, 255);
                int b = random.Next(0, 255);
                bitmap.SetPixel(x, y, Color.FromArgb(255, r, g, b));
                snsPictureBox1.Image = bitmap;
                evtShow.Reset();//复原等待状态
            }
        }

        private void snsPictureBox1_Paint(object sender, PaintEventArgs e)
        {
            string strTime="";
            strTime += string.Format("Size:{0}x{1}", snsPictureBox1.ImgWidth, snsPictureBox1.ImgHeight);
            strTime += string.Format("     Scale:{0:F2}", snsPictureBox1.SnsScale);
            strTime += string.Format("     ShowFps:{0:F1}", snsPictureBox1.ShowFps);
            strTime += string.Format("     ImgId:{0}", total);
            snsPictureBox1.ShowString(strTime, new PointF(snsPictureBox1.XSpace + 1, snsPictureBox1.YSpace + 1), false);
        }

        private void snsPictureBox1_DoubleClick(object sender, EventArgs e)
        {
            snsPictureBox1.Init();
        }

    }
}
